import babel from "@babel/core"
import { AstroError } from "astro/errors"
import fs from 'fs/promises'
import chokidar from "chokidar";
import debounce from "lodash/debounce";

const SourcePath = "src/components/BrowserVersionWarn/index.ts"
const TargetPath = "src/components/BrowserVersionWarn/index.js"

export async function transform() {
  const res = await babel.transformAsync(await fs.readFile(SourcePath, "utf-8"), {
    filename: "114.ts",
    presets: ["@babel/preset-env", "@babel/preset-typescript"],
    "plugins": ["@babel/plugin-transform-modules-commonjs"]
  })
  if (res) await fs.writeFile(TargetPath, res.code)
  else throw new AstroError("[GenerateBrowserWarn] Babel transform error")
}

const debounceTransform = debounce(transform, 1000)

export default async function () {
  await transform()
  chokidar.watch(SourcePath).on("change", async () => {
    await debounceTransform()
  })
}